/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package control;


import au.com.bytecode.opencsv.CSVReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.myfaces.custom.fileupload.UploadedFile;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.List;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
/**
 *
 * @author juampi
 */
public class ControlSubirNota {
        private String codigoCriterio;
        private UploadedFile file;
        
        public String getCodigoCriterio(){
            return "";
        }
        public void setCodigoCriterio(String codigoCriterio){
            this.codigoCriterio=codigoCriterio;
        }
        public UploadedFile getFile(){
            return file;
        }
        public void setFile(UploadedFile uf){
            file=uf;
        }
        public void guardar(ActionEvent ae){
            if(file.getName().endsWith("csv")){
                cargarDeCvs(file);
            }else if(file.getName().endsWith("xls")){
                cargarDeXls(file);
            }else{

            }
        }
        private void cargarDeXls(UploadedFile uf){
            try{
                InputStream inp=file.getInputStream();
                HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(inp));
                int n=wb.getNumberOfSheets();
                HSSFSheet ss=wb.getSheetAt(0);
                for(Row row : ss){
                    int i=0;
                    Iterator<Cell> cls=row.iterator();
                    String id=toString(cls.next());
                    String nc=toString(cls.next());
                    String ps=toString(cls.next());
                    JOptionPane.showMessageDialog(null,id+" - "+nc+" - "+ps);
                }
            }catch(Exception e){

            }
            
        }
        private void cargarDeCvs(UploadedFile uf){
            try {
                CSVReader csvReader = new CSVReader(new InputStreamReader(uf.getInputStream(), "UTF-8"), CSVReader.DEFAULT_SEPARATOR, CSVReader.DEFAULT_QUOTE_CHARACTER, 1);
                List<String[]> myEntries = csvReader.readAll();
                for (String[] entry : myEntries) {
                    String data="";
                    for(String s: entry){
                        data=data+" - "+s;
                    }
                    JOptionPane.showMessageDialog(null,data);
                }
            } catch (IOException ex) {
                Logger.getLogger(ControlSubirNota.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        public void descargar(ActionEvent ae){
        try{
            File ficheroXLS = new File("/home/juampi/e.xls");
            FacesContext ctx = FacesContext.getCurrentInstance();
            FileInputStream fis;

            fis = new FileInputStream(ficheroXLS);

            byte[] bytes = new byte[1000];
            int read = 0;

            if (!ctx.getResponseComplete()) {
               String fileName = ficheroXLS.getName();
               String contentType = "application/vnd.ms-excel";
               //String contentType = "application/pdf";
               HttpServletResponse response =(HttpServletResponse) ctx.getExternalContext().getResponse();
               response.setContentType(contentType);
               response.setHeader("Content-Disposition","attachment;filename=\"" + fileName + "\"");
               ServletOutputStream out;

                out = response.getOutputStream();

                while ((read = fis.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }

               out.flush();
               out.close();
               System.out.println("\nDescargado\n");
               ctx.responseComplete();
            }
            } catch (Exception ex) {

            }


        }
        private String toString(Cell cell){
            String res="";
            switch(cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
            res+=cell.getRichStringCellValue().getString();
            break;
            case Cell.CELL_TYPE_NUMERIC:
            if(DateUtil.isCellDateFormatted(cell)) {
                res+=cell.getDateCellValue().toString();
            } else {
                res+= (int)cell.getNumericCellValue();
            }
            break;
            case Cell.CELL_TYPE_BOOLEAN:
            res+=cell.getBooleanCellValue();
            break;
            case Cell.CELL_TYPE_FORMULA:
            res+=cell.getCellFormula();
            break;
            default:
            }
            return res;
        }
        
}
